﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;


public partial class Boundary_FrmHumanResources : System.Web.UI.Page
{
    private CtrlProfile ctrlProfile = new CtrlProfile();
    private CtrlRole ctrlRole = new CtrlRole();

    private string profile = "";
    private string role = "";

    private CtrlHumanResource ctrlHumanResource
    {
        get
        {
            return (CtrlHumanResource)(Session["ctrlHumanResource"]);
        }
        set
        {
            (Session["ctrlHumanResource"]) = value;
        }
    }

    private string changing
    {
        get
        {
            return (string)(ViewState["changing"]);
        }
        set
        {
            ViewState["changing"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        consultando.Visible = false;
        modificando.Visible = false;
        ninguno.Visible = true;
        insertando.Visible = false;

        //Redirection if there is no cookie.
        HttpCookie cookie = Request.Cookies.Get("requmanaLogin");
        if (cookie == null)
        {
            Response.Redirect("FrmLogin.aspx");
        }
        else
        {
            profile = cookie.Values[3];
            role = cookie.Values[4];
        }

        // Inicializa control de recurso humano
        if (Session["ctrlHumanResource"] == null)
        {
            ctrlHumanResource = new CtrlHumanResource();
        }

        // Carga y configura el ctlGridView
        if (Int32.Parse(cookie.Values[3]) == 0)
        {
            ctlGridView.setDataSource(ctrlHumanResource.getData());
        }
        else {
            ctlGridView.setDataSource(ctrlHumanResource.getDataC(Int32.Parse(cookie.Values[5])));
        }

        ctlGridView.Select += new MyEventHandler(ctlGridView_Select);
        ctlGridView.Modify += new MyEventHandler(ctlGridView_Modify);
        ctlGridView.Eliminate += new MyEventHandler(ctlGridView_Eliminate);

        // Deshabilita campos
        if (!(IsPostBack))
        {
            disableFields();
            btnAdd.Enabled = true;
        }

        // Inicializa ComboBox
        if (!IsPostBack)
        {
            ctlComboBoxProfile.setDataSource(ctrlProfile.getData(), "Description", "Profile");
            ctlComboBoxRole.setDataSource(ctrlRole.getData(), "Description", "Role");
        }
        
    }

    private bool validateFields()
    {
        bool valid = true;

        hideValidations();

        Regex regularNotNull = new Regex("^(.{1,50})$");
        Regex regularNull = new Regex("^(.{0,50})$");
        Regex email = new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+" + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$");
        Regex phone = new Regex("^((\\(\\+?\\d{1,3}\\))? ?[28]\\d{3}-?\\d{4})$");//

        if (txtUsername.Text == "")
        {
            userValidation.Visible = true;
            userValComment.Visible = true;
            valid = false;
        }
        else
        {
            if (!(regularNotNull.IsMatch(txtUsername.Text)))
            {
                userValidation.Visible = true;
                userValFormat.Visible = true;
                valid = false;
            }
        }

        if (txtPassword.Text == "")
        {
            passValidation.Visible = true;
            passValComment.Visible = true;
            valid = false;
        }
        else
        {
            if (!(regularNotNull.IsMatch(txtPassword.Text)))
            {
                passValidation.Visible = true;
                passValFormat.Visible = true;
                valid = false;
            }
        }
        if (txtConfirm.Text == "")
        {
            confirmValidation.Visible = true;
            confirmValComment.Visible = true;
            valid = false;
        }
        else
        {
            if (!(regularNotNull.IsMatch(txtConfirm.Text)))
            {
                confirmValidation.Visible = true;
                confirmValFormat.Visible = true;
                valid = false;
            }
        }

        if (txtConfirm.Text == "")
        {
            confirmValidation.Visible = true;
            confirmValComment.Visible = true;
            valid = false;
        }
        else
        {
            if (!(regularNotNull.IsMatch(txtConfirm.Text)))
            {
                confirmValidation.Visible = true;
                confirmValFormat.Visible = true;
                valid = false;
            }
        }

        
        if (txtPassword.Text != txtConfirm.Text)
        {
            confirmValidation.Visible = true;
            matchValComment.Visible = true;
            valid = false;
        }

        if (txtFirstName.Text == "")
        {
            firstnameValidation.Visible = true;
            firstnameValComment.Visible = true;
            valid = false;
        }
        else
        {
            if (!(regularNotNull.IsMatch(txtFirstName.Text)))
            {
                firstnameValidation.Visible = true;
                firstnameValFormat.Visible = true;
                valid = false;
            }
        }

        if (txtLastName.Text == "")
        {
            lastnameValidation.Visible = true;
            lastnameValComment.Visible = true;
            valid = false;
        }
        else
        {
            if (!(regularNotNull.IsMatch(txtLastName.Text)))
            {
                lastnameValidation.Visible = true;
                lastnameValFormat.Visible = true;
                valid = false;
            }
        }
        
        if (txtEmail.Text != "")
        {
            if ((!(email.IsMatch(txtEmail.Text)))|| (!(regularNull.IsMatch(txtEmail.Text))))
            {
                emailValidation.Visible = true;
                emailValComment.Visible = true;
                valid = false;
            }
        }
        if (txtPhone.Text != "")
        {
            if (!(phone.IsMatch(txtPhone.Text)))
            {
                //MUESTRA ERROR EN VENTANITA SOBRE EL FORMATO.
                phoneValidation.Visible = true;
                phoneValComment.Visible = true;
                valid = false;
            }
        }

        return valid;
    }

    private void hideValidations()
    {
        userValidation.Visible = false;
        userValComment.Visible = false;
        userValFormat.Visible = false;
        passValidation.Visible = false;
        passValComment.Visible = false;
        passValFormat.Visible = false;
        confirmValidation.Visible = false;
        confirmValComment.Visible = false;
        confirmValFormat.Visible = false;
        matchValComment.Visible = false;
        firstnameValidation.Visible = false;
        firstnameValComment.Visible = false;
        firstnameValFormat.Visible = false;
        lastnameValidation.Visible = false;
        lastnameValComment.Visible = false;
        lastnameValFormat.Visible = false;
        emailValidation.Visible = false;
        emailValComment.Visible = false;
        phoneValidation.Visible = false;
        phoneValComment.Visible = false;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        bool admin = (profile == "0");

        consultando.Visible = false;
        modificando.Visible = false;
        ninguno.Visible = false;
        insertando.Visible = true;

        clearFields();

        if (admin)
        {
            changing = "inserting";
            enableFields(0);
            ctlMessage1.showMessage("info", "Puede digitar la informacion del recurso humano.");
        }

        ctlGridView.hideButtons();
    }

    protected void ctlGridView_Select(object sender, int iVal)
    {
        consultando.Visible = true;
        modificando.Visible = false;
        ninguno.Visible = false;
        insertando.Visible = false;

        loadFields(ctrlHumanResource.getHumanResource(iVal));
        disableFields();
        btnAdd.Enabled = true;
    }

    protected void ctlGridView_Modify(object sender, int iVal)
    {
        bool admin = (profile == "0");
        bool leader = (role == "0");

        consultando.Visible = false;
        modificando.Visible = true;
        ninguno.Visible = false;
        insertando.Visible = false;

        if (admin || leader)
        {
            loadFields(ctrlHumanResource.getHumanResource(iVal));
            changing = "modifying";
            enableFields(1);
            ctlMessage1.showMessage("info", "Puede editar la informacion del recurso humano.");
        }

        btnAdd.Enabled = false;

        ctlGridView.hideButtons();
    }

    protected void ctlGridView_Eliminate(object sender, int iVal)
    {
        bool admin = (profile == "0");

        if (admin)
        {
            ctrlHumanResource.deleteHumanResource(iVal);
            ctlMessage2.showMessage("success", "El recurso humano ha sido eliminado satisfactoriamente.");
            Response.Redirect("FrmHumanResources.aspx");
        }
    }

    private void loadFields(HumanResource resource)
    {
        txtUsername.Text = resource.sUsername;
        txtFirstName.Text = resource.sFirstName;
        txtLastName.Text = resource.sLastName;
        txtEmail.Text = resource.sEmail;
        txtPhone.Text = resource.sPhone;
        ctlComboBoxProfile.setSelectedId(resource.iProfile.ToString());
        ctlComboBoxRole.setSelectedId(resource.iRole.ToString());
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        bool admin = (profile == "0");
        bool leader = (role == "0");

        consultando.Visible = false;
        modificando.Visible = false;
        ninguno.Visible = true;
        insertando.Visible = false;

        if (admin || leader)
        {
            if (validateFields())
            {
                if (changing.Equals("modifying"))
                {
                    ctrlHumanResource.setHumanResource(txtUsername.Text, txtFirstName.Text, txtLastName.Text, txtConfirm.Text, txtPhone.Text, txtEmail.Text, int.Parse(ctlComboBoxRole.getSelectedId()), int.Parse(ctlComboBoxProfile.getSelectedId()));
                    ctlMessage1.showMessage("success", "El recurso humano ha sido modificado satisfactoriamente.");
                    Response.Redirect("FrmHumanResources.aspx");
                }

                if (changing.Equals("inserting"))
                {

                    ctrlHumanResource.addHumanResource(txtUsername.Text, txtFirstName.Text, txtLastName.Text, txtConfirm.Text, txtPhone.Text, txtEmail.Text, int.Parse(ctlComboBoxRole.getSelectedId()), int.Parse(ctlComboBoxProfile.getSelectedId()));
                    ctlMessage1.showMessage("success", "El recurso humano ha sido agregado satisfactoriamente.");
                    Response.Redirect("FrmHumanResources.aspx");
                }

                changing = "";
                //clearFields();
                disableFields();
                ctlGridView.update();
            }
        }
        ctlGridView.showButtons();
       
        btnAdd.Enabled = true;
    }

    protected void btnCancelar_Click(object sender, EventArgs e)
    {
        consultando.Visible = false;
        modificando.Visible = false;
        ninguno.Visible = true;
        insertando.Visible = false;

        changing = "";
        clearFields();
        disableFields();
        btnAdd.Enabled = true;

        ctlGridView.showButtons();
    }

    public void clearFields()
    {
        txtUsername.Text = "";
        txtFirstName.Text = "";
        txtLastName.Text = "";
        txtEmail.Text = "";
        txtPhone.Text = "";
        txtPassword.Text = "";
        txtConfirm.Text = "";
    }

    //Parameters:
    //0 if new user
    //1 if old user
    public void enableFields(int userRange)
    {
        
        txtFirstName.Enabled = true;
        txtLastName.Enabled = true;
        txtEmail.Enabled = true;
        txtPhone.Enabled = true;
        btnSave.Enabled = true;
        btnAdd.Enabled = true;
        btnCancelar.Enabled = true;
        ctlComboBoxProfile.Enabled = true;
        ctlComboBoxRole.Enabled = true;
        if (userRange == 0)
        {
            txtUsername.Enabled = true;
            txtPassword.Enabled = true;
            txtConfirm.Enabled = true;
        }
        else
        {
            txtPassword.Enabled = true;
            txtConfirm.Enabled = true;
        }
    }

    public void disableFields()
    {
        txtUsername.Enabled = false;
        txtFirstName.Enabled = false;
        txtLastName.Enabled = false;
        txtPassword.Enabled = false;
        txtConfirm.Enabled = false;
        txtEmail.Enabled = false;
        txtPhone.Enabled = false;
        btnAdd.Enabled = false;
        btnSave.Enabled = false;
        btnCancelar.Enabled = false;
        ctlComboBoxProfile.Enabled = false;
        ctlComboBoxRole.Enabled = false;
    }
}
